from datetime import datetime

import akshare as ak
import numpy as np
from retry import retry

from python_quant.common.common import ths_billboard
from python_quant.stock.MYTT_EXT import REF
from python_quant.stock.myTT import HHV, BARSLAST, IF, CROSS, MA


def ths_tech_trade():
    url = 'https://eq.10jqka.com.cn/open/api/hot_list/v1/investment/tech_trade.txt'
    return ths_billboard(url)


def ths_trend_invest():
    url = 'https://eq.10jqka.com.cn/open/api/hot_list/v1/investment/trend_invest.txt'
    return ths_billboard(url)


def valuation(code):
    """
    估价
    """
    now_date = datetime.now().strftime('%Y%m%d')
    stock_zh_a_hist_df = ak.stock_zh_a_hist(symbol=code, period="daily", start_date="19910101", end_date=now_date,
                                            adjust="qfq")
    closes = stock_zh_a_hist_df['收盘'].values
    last_close = closes[-1]
    mas = MA(closes, len(closes))
    ma_all = mas[-1]
    mid_high = max(closes) / 2
    min_price = min(ma_all, mid_high)

    return last_close, ma_all, mid_high, min_price


def floor_out(C, H, L, O):
    X = HHV(H, 5)
    X = np.nan_to_num(X, nan=-1)
    V = REF(X, 1)
    V = np.nan_to_num(V, nan=-1)
    VAR111 = C > V
    VAR222 = BARSLAST(VAR111)
    D = REF(L, 1)
    D = np.nan_to_num(D, nan=-1)
    B = IF(C > L, L, D)
    A = REF(B, VAR222)
    G = IF(D > L, L, D)
    OUTLINE = IF(VAR111, G, A)
    S = CROSS(OUTLINE, C)
    B = CROSS(C, OUTLINE)
    return S, B


@retry(tries=10, delay=10, backoff=1)
def tech_stocks(code_list):
    """
    技术面
    """
    codes = list()
    for code in code_list:
        is_true = price_lower_than_ma_all_and_mid_high_and_lower_x(code)
        if is_true:
            codes.append(code)
    return codes


def price_lower_than_ma_all_and_mid_high_and_lower_x(code):
    """
    价格低于折半价和历史均价线,低于20%
    """
    last_close, ma_all, mid_high, min_price = valuation(code)
    if last_close < min_price and (last_close - min_price) / min_price * 100 < -20:
        return True
    return False
